#!/usr/bin/python -OO

# $Id: tpa_send.py 227 2013-05-30 06:52:52Z chengxin.cai $

import sys, os, stat
from amqp import RoutingKey

fifo_def = os.path.join(os.environ.get('MY_SPROOT', '.'), 'amqp-tpa')

def tpa_send(client, routing_key, msg, fifo=fifo_def):

    # Message format is:
    # <bodyLen>:<routing_key>:<ts_utc>:<ts_lct>:<client_name>:<msg>
    import time
    ts_utc = int(time.time() * 1e6)
    ts_lct = int(ts_utc - time.altzone * 1e6)

    msgstr = '%s:%d:%d:%s:%s' % ( routing_key, ts_utc, ts_lct, client, 
                                  msg.replace('\\t', '\t') )

    num_chars = len(msgstr);
    realmsg = '%d:%s\n' % (num_chars, msgstr)

    if __debug__:
        sys.stdout.write(realmsg)

    if not os.path.exists(fifo):
        raise OSError('%s not exist' % fifo)

    f_mode = os.stat(fifo).st_mode
    if not stat.S_ISFIFO(f_mode):
        raise TypeError('%s is not a valid named pipe' % fifo)

    if not stat.S_IWUSR & f_mode:
        raise AttributeError('write permission denied by %s' % fifo)

    fd = os.open(fifo, os.O_RDWR|os.O_ASYNC|os.O_NONBLOCK)
    try:
        os.write(fd, realmsg)
    finally:
        os.close(fd)
     
def tpa_send_rpc(client, routing_key, msg, host, port):
    import xmlrpclib

    server = xmlrpclib.Server('http://%s:%d' % (host, port))

    server.accept(client, routing_key, msg)

if __name__ == '__main__':

    from optparse import OptionParser

    usage = '''Usage: %prog [--fifo=<fifo>] [--remote --ip=<ip> --port=<port>] 
                   CLIENT_NAME ROUTING_KEY MSG'''
   
    parser = OptionParser(usage = usage)

    parser.add_option('-f', '--fifo',  dest = 'fifo', 
           action='store',  default = fifo_def,
           help='specify the location of the named pipe, [default: %default]')

    parser.add_option('-r', '--remote',  dest = 'remote', 
           action='store_true', 
           help='whether send text message to remote host')

    parser.add_option('-i', '--ip',  dest = 'ip', 
           action='store', 
           help='specify the ip of remote host if --remote is set')

    parser.add_option('-p', '--port',  dest = 'port', 
           action='store', type=int, default=8000,
           help='specify the port of remote host if --remote is set')

    (opts, args) = parser.parse_args()

    if len(args) < 3:
        parser.print_help()
        sys.exit(1)

    client, routing_key, msg = args

    if opts.remote:
        tpa_send_rpc(client, routing_key, msg, opts.ip, opts.port)
    else:
        tpa_send(client, routing_key, msg, opts.fifo)

    sys.exit(0)
    
